import 'dart:convert';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/gen_a/A.dart';
import 'package:exams_app/home_module/account_set_module/account_logic.dart';
import 'package:exams_app/home_module/exams_module/view.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:exams_app/widget/hexcolor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
// import 'package:camera/camera.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart' as path_provider;
import 'dart:io';
import 'package:rtmp_publisher/camera.dart';

import '../../main.dart';
import 'logic.dart';

// import '../main.dart';
// import 'account_set_module/account_logic.dart';

class ShuaFacePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ShuaFacePageState();
  }
}

class ShuaFacePageState extends State {


  final AccountLogic accountLogicClogic = Get.put(AccountLogic());

  HomeModuleLogic logic = Get.put(HomeModuleLogic());

  CameraController controller;
  // List<CameraDescription> cameras;

  // String streamURL = "rtmp://push.dtcloud360.com/DTCloud/DTCloud?auth_key=1629272869-0-0-794c45ccf2ebf794071f3e19216c5ca5";

  var imageFile0;

  /// 修改名称 身份证 号码 '
  void upDataWithNameAnCard(var ai_face) async {

    BotToast.showLoading();

    var params = {
      'access_token': await PersistentStorage().getStorage('acctoken'),
      'uid':2,
      'partner_id': 3,
      'model': 'res.partner',
      'form-field-char-ai_face': ai_face,

      // 'fields': 'form-field-char-name,form-field-char-sfz,form-field-char-sfz_heads,form-field-char-sfz_tails,',
      // 'domain': "[('user_id', '=', ${await PersistentStorage().getStorage('uid')})]",  //#我的表达式
    };

    String result = await DioUtils(
            url: await PersistentStorage().getStorage('urlStr'))
        .post(
            '/api/v1/write/${await PersistentStorage().getStorage('partner_id')}',
            data: params);

    Map json = jsonDecode(result);

    if (json['errmsg'] == 'ok') {
      // Get.to(ShuaFacePage());

      BotToast.showText(text: '实名认证成功');


      // Get.back();
      // Get.back();
      // Get.back();'
      // Get.back();
      Get.offAll(HomeModulePage());


    }
  }

  @override
  void initState() {

    controller =
        CameraController(cameras[1], ResolutionPreset.medium, enableAudio: false);

    controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });

    super.initState();
  }

  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // if (!controller.value.isInitialized) {
    //   BotToast.showText(text: '暂未检测到摄像头,请检测');
    //
    //   return Container();
    // }

    return Scaffold(
      appBar: AppBar(
        title: Text('人脸采集'),
        actions: [
          TextButton(onPressed: ()async{
            print('111');
            if(imageFile0==null){
              BotToast.showText(text: '请先拍照');
              return;
            }
            var imageys = await imageCompressAndGetFile(File(imageFile0));

            List bytes = await imageys.readAsBytes();

            String bs64 = base64Encode(bytes);

            String bs64Image = bs64;



            upDataWithNameAnCard(bs64Image);





          }, child: Text('提交',style: TextStyle(color: Colors.white),)),
        ],
      ),
      body: Stack(
        // padding: EdgeInsets.all(0),
        children: [
          // _cameraPreviewWidget(),
          Container(
            // color: Colors.red,
            width: Get.width,
            margin: EdgeInsets.only(bottom: 150),
            // margin: EdgeInsets.all(20),
            clipBehavior: Clip.antiAliasWithSaveLayer,
            // color: Colors.red,

            //边框设置
            decoration: new BoxDecoration(
              shape: BoxShape.circle,
              // color: Colors.red
            ),
            child:Align(
              alignment: Alignment.center,
              child: imageFile0==null?CameraPreview(
                controller,
                // child:imageFile0==null?Container():Image.file(File(imageFile0),fit: BoxFit.fill,) ,
              ):Image.file(File(imageFile0),fit: BoxFit.fill,),
            ),
          ),
          Container(
            margin: EdgeInsets.all(20),
            child:  Align(
              alignment: Alignment.bottomCenter,
              child:  Row(
                children: [
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: 25, right: 0, left: 0),
                      width: Get.width,
                      height: 45,
                      child: RaisedButton(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(22),
                        ),
                        color: Theme.of(context).primaryColor,
                        onPressed: () async {
                          if(imageFile0 == null){
                            String timestamp() =>
                                DateTime.now().millisecondsSinceEpoch.toString();
                            if (!controller.value.isInitialized) {
                              print('Error: select a camera first.');
                              return null;
                            }
                            // getApplicationDocumentsDirectory  文档目录
                            final Directory extDir =
                            await getApplicationDocumentsDirectory();
                            final String dirPath =
                                '${extDir.path}/Pictures/flutter_test';
                            print(dirPath);
                            await Directory(dirPath).create(recursive: true);
                            final String filePath = '$dirPath/${timestamp()}.jpg';
                            print(filePath);



                            try {

                              await controller.takePicture(filePath);
                              imageFile0 = filePath;
                              // XFile file = await controller.takePicture();
                              // imageFile0 = file.path;
                              print('保存成功');

                              // var imageys = await imageCompressAndGetFile(File(filePath));
                              //
                              // List bytes = await imageys.readAsBytes();
                              //
                              // String bs64 = base64Encode(bytes);
                              //
                              // String bs64Image = 'data:image/jpg;base64,${bs64}';
                              //
                              // logic.requestDataWithAIface(bs64Image).then((value){
                              //
                              //   if(value['errcode']==-100){
                              //     BotToast.showText(text: '摄像头内未检测到人脸');
                              //     return;
                              //   }
                              //
                              //   imageFile0 = filePath;
                              //   setState(() {
                              //
                              //   });
                              //
                              // });
                                setState(() {

                                });

                              // Get.to(DisplayPictureScreen(
                              //   imagePath: file.path,
                              // ));
                            } on CameraException catch (e) {
                              print('保存失败');
                              print(e);
                              return null;
                            }
                          }else{
                                      imageFile0 = null;
                                      setState(() {

                                      });
                          }
                        },
                        child: Text(imageFile0==null?'拍照':
                          '重拍',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ),

                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
